package FlowGram.Application.Parser.Actions.Control;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import FlowGram.Application.Parser.FinchParser;
import FlowGram.Application.Parser.FinchParserException;
import FlowGram.Application.Parser.Controllers.FinchController;


/**
 * 
 * @author thackray
 *
 */
public class Repeat extends ControlAction {

	
	protected int numTimes;
	
	
	public Repeat(FinchParser parser){
		super(parser);
	}
	public Repeat(){
		super();
	}
	
	public static boolean matches(String s){
		return s.matches("^repeat.+");
	}
	public static boolean matchesEnd(String s){
		return s.matches("^endrepeat$");
	}
	public static String syntax(){
		return "repeat <number> times\n\t<code>\nendrepeat";
	}
	public void setNumTimes(int times){
		this.numTimes = times;
	}
	public int getNumTimes(){
		return this.numTimes;
	}
	
	@Override
	public String toCode(int indent) {
		return "repeat "+this.numTimes+" times\n"+this.innerFlow.toCode(indent+1)+"\n"+this.getIndent(indent)+"endrepeat";
	}
	@Override
	public String toHTML(String idPrefix) {
		return "repeat "+this.numTimes+" times"+this.innerFlow.toHTML(idPrefix)+"endrepeat";
	}

	@Override
	public void execute(FinchController controller) {
		this.ensureController(controller);
		for(int i=0; i < this.numTimes; i++){
			this.innerFlow.execute();
		}
	}

	@Override
	public String logMessage() {
		return "repeating "+this.numTimes+" times";
	}

	@Override
	public void parse(String statement) throws FinchParserException {
		Pattern p = Pattern.compile("^repeat\\s+(\\d+)\\s+times$");
		Matcher matcher = p.matcher(statement);
		while(matcher.find()){
			if(matcher.group(1) != null){
				this.numTimes = Integer.parseInt(matcher.group(1));
				String buffer = "";
				String line = this.parser.getNextStatement();
				int sawrepeat = 0;
				while(true){
					if(matchesEnd(line)){
						if(sawrepeat == 0){
							break;
						}
						sawrepeat--;
					}
					if(matches(line)){
						sawrepeat++;
					}
					buffer += line+"\n";
					line = this.parser.getNextStatement();
				}
				FinchParser parse = new FinchParser();
				this.innerFlow = parse.Parse(buffer);
			}
		}
	}

}
